(function ($) {
    "use strict";

    $.fn.treegridData = function (options, param) {
        //如果是调用方法
        if (typeof options == 'string') {
            return $.fn.treegridData.methods[options](this, param);
        }
        
        //如果是初始化组件
        options = $.extend({}, $.fn.treegridData.defaults, options || {});
        $.fn.treegridData.options=options
        var target = $(this);
        target.getColumns=function(tr,item){
            $.each(options.columns, function (index, column) {
                var td = $('<td></td>');
                var _tempText = ''
                if(column.field != '' && column.field != undefined){
                    var isParentNode = item[options.parentColumn] == '' || item[options.parentColumn] == null || item[options.parentColumn] == '0'

                    var _baseText=item[column.field]
                    if(isParentNode && options.boldRootNodes){
                        _baseText ='<p class=\"rootnodes\">'+item[column.field]+'</p>'
                    }

                    var _exText = ''
                    if(column.exField && item[column.exField]){
                        _exText = '<p class=\"exField\">'+item[column.exField]+'</p>'
                    }
                    if(options.onlyrootExField && !isParentNode){
                        _exText =''
                    }
                    _tempText = _baseText + _exText
                    td.html(_tempText);
                }else if(column.html){
                    if(typeof(column.html) == 'function'){
                        td.html(column.html(item,tr))
                    }else{
                        td.html(column.html)    
                    }
                    
                }
                if(column.w){
                    td.attr('width',column.w)
                }
                if(column.style){
                    td.css(column.style)
                }
                tr.append(td);
            });
            j++
        }
        //debugger;
        //得到根节点
        target.getRootNodes = function (data) {
            var result = [];
            $.each(data, function (index, item) {
                if (item[options.parentColumn] == '0') {
                    result.push(item);
                }
            });
            return result;
        };
        var j = 0;
        //递归获取子节点并且设置子节点
        target.getChildNodes = function (data, parentNode, parentIndex, tbody) {
            var nowParentIndex = parentIndex
            $.each(data, function (i, item) {
                if (item[options.parentColumn] == parentNode[options.id]) {
                    var tr = $('<tr></tr>');
                    target.getColumns(tr,item)
                    tr.addClass('treegrid-' + j);
                    tr.addClass('treegrid-parent-' + nowParentIndex);
                    tr.data('listdata',item[options.textColumn]+'-'+item[options.parentColumn]+'-'+ item[options.id]+'-'+j+'-'+nowParentIndex)
                    tbody.append(tr);
                    target.getChildNodes(data, item, j, tbody)
                    
                }
            });
        };
        target.addClass('table');
        if (options.striped) {
            target.addClass('table-striped');
        }
        if (options.bordered) {
            target.addClass('table-bordered');
        }
        if (options.url) {
            $.ajax({
                type: options.type,
                url: options.url,
                data: options.ajaxParams,
                dataType: "JSON",
                success: function (data, textStatus, jqXHR) {
                    
                    var _data = data.data;
                    //debugger;
                    if(options.showHead){
                        //构造表头
                        var thr = $('<tr></tr>');
                        $.each(options.columns, function (i, item) {
                            var th = $('<th style="padding:10px;"></th>');
                            th.text(item.title);
                            thr.append(th);
                        });
                        var thead = $('<thead></thead>');
                        thead.append(thr);
                        target.append(thead);
                    }
                    $.fn.treegridData.options.data = _data

                    //构造表体
                    var tbody = $('<tbody></tbody>');
                    if(_data){
                        var rootNode = target.getRootNodes(_data);
                        $.each(rootNode, function (i, item) {
                            var tr = $('<tr></tr>');
                            target.getColumns(tr,item)
                            tr.addClass('treegrid-' + j);
                            tr.data('listdata',item[options.textColumn]+'-'+item[options.parentColumn]+'-'+ item[options.id]+'-'+j)
                            tbody.append(tr);
                            target.getChildNodes(_data, item, j, tbody);
                        });
                    }
                    
                    target.html('')
                    target.append(tbody);
                    target.treegrid({
                        expanderExpandedClass: options.expanderExpandedClass,
                        expanderCollapsedClass: options.expanderCollapsedClass
                    });
                    target.on('click','tbody tr',function(el){
                        
                        if($(el.target).hasClass('treegrid-expander glyphicon'))return
                        if(options.onclickNode) options.onclickNode($(el.currentTarget))    
                    })
                    
                    if (!options.expandAll) {
                        target.treegrid('collapseAll');
                    }
                    options.renderSuccess()
                },
                complete:function(){
                    options.renderComplete()
                }
            });
        }
        else {
            //也可以通过defaults里面的data属性通过传递一个数据集合进来对组件进行初始化....有兴趣可以自己实现，思路和上述类似
        }
        return target;
    };

    $.fn.treegridData.methods = {
        getAllNodes: function (target, data) {
            return target.treegrid('getAllNodes');
        },
        getParentNode:function(target, data){
            return target.treegrid('getParentNode');
        },
        getOptions:function(target, data){
            if(data){
                return $.fn.treegridData.options[data] 
            }else{
                return $.fn.treegridData.options
            }
        },
        getAllNodesData: function (target, data) {
            return $.fn.treegridData.options.data 
        },
        getNodeData:function(target, data){
            var _options = $.fn.treegridData.options
            var _data = _options.data
            var _dataId = target.data('listdata').split('-')[2]
            var _item=''
            $.each(_data,function(i,item){
                if(_dataId == item[_options.id]){
                    _item = item;
                }
            })
            return _item
        },
        getParentNodeData:function(target, data){
            var _options = $.fn.treegridData.options
            var _data = _options.data
            //console.log(target)
            var _dataPid = target.data('listdata').split('-')[1]
            var _item=''
            $.each(_data,function(i,item){
                if(_dataPid == item[_options.id]){
                    _item = item;
                }
            })
            return _item
            // if(target.treegrid('getParentNode')){
            //     var _data = target.treegrid('getParentNode').data('listdata').split('-')
            //     return {
            //         name:_data[0],
            //         pid:_data[1]=='undefined'?'0':_data[1],
            //         id:_data[2],
            //         ids:_data[3],
            //         pids:_data[4]=='undefined'?'':_data[4]
            //        };
            // }else{
            //     return{
            //         name:'',
            //         pid:'',
            //         id:'',
            //         ids:'',
            //         pids:''
            //     }
            // }
            
            
   
        }
        //组件的其他方法也可以进行类似封装........
    };
    $.fn.treegridData.defaults = {
        id: 'id',
        parentColumn: 'pid',
        textColumn:'name',
        data: [],    //构造table的数据集合
        type: "GET", //请求数据的ajax类型
        url: null,   //请求数据的ajax的url
        ajaxParams: {}, //请求数据的ajax的data属性
        expandColumn: null,//在哪一列上面显示展开按钮
        expandAll: true,  //是否全部展开
        striped: false,   //是否各行渐变色
        bordered: false,  //是否显示边框
        columns: [],
        showHead:false,//是否展示表头
        boldRootNodes:true,//根节点默认加粗
        onlyrootExField:true,//只有跟节点显示exField内容
        expanderExpandedClass: 'glyphicon glyphicon-chevron-down',//展开的按钮的图标
        expanderCollapsedClass: 'glyphicon glyphicon-chevron-right',//缩起的按钮的图标
        onclickNode:function(){},
        renderSuccess:function(){},
        renderComplete:function(){}        
    };
})(jQuery);